<?php

namespace App\Kuafu\WaiMai\Service;

use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Mqtt\Service\MqttService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiCacheEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiCodeEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use App\Kuafu\WaiMai\Jobs\WaiMaiDelayTask;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WaiMaiProductService
{
    /**
     * 店铺下的外卖菜品列表
     * @param int $shopId
     * @throws WaiMaiException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getShopProducts(int $shopId, int $sourceType = 0)
    {
        $lists = collect(Cache::remember(WaiMaiCacheEnum::getShopWaiMaiProducts($shopId, $sourceType), 86400,
            function () use ($sourceType, $shopId) {
                return array_merge(BaseWaiMai::getIns(WaiMaiDBEnum::SOURCE_TYPE_MT_WM, $shopId)
                                             ->getProductPage(0, WaiMaiDBEnum::PRODUCT_MAX_PAGE_NUM)['data'],
                    BaseWaiMai::getIns(WaiMaiDBEnum::SOURCE_TYPE_ELM, $shopId)
                              ->getProductPage(0, WaiMaiDBEnum::PRODUCT_MAX_PAGE_NUM)['data']);
            }))
            ->map(function ($item) {
                $item['sourceTypeText'] = CodeEnum::SOURCE_TYPES[$item['sourceType'] ?? ''] ?? '';
                return $item;
            })
            ->toArray();

        if ($sourceType == 0) {
            return $lists;
        }

        return collect($lists)->filter(function ($item) use ($sourceType) {
            if ($item['sourceType'] == $sourceType) {
                return true;
            }

            return false;
        })->values();
    }
}
